package com.soft.mainsite.module.staticstrategy.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.soft.mainsite.module.staticstrategy.dao.TemplateManageDao;
import com.soft.mainsite.module.staticstrategy.dao.TemplateRelationDao;
import com.soft.mainsite.module.staticstrategy.entity.StaticStrategy;
import com.soft.mainsite.module.staticstrategy.entity.TemplateManage;
import com.soft.mainsite.module.staticstrategy.entity.TemplateRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * TemplateRelationServiceImpl.java 此类用于模板切分关系Service
 *
 * @author:刘兴家
 * @date:2019/4/24 0011
 * @remark:
 */
@Service
public class TemplateRelationServiceImpl implements TemplateRelationService {

	@Autowired
	private TemplateRelationDao templateRelationDao;

	@Autowired
	private TemplateManageDao templateManageDao;


	/**
	 * 添加
	 * @param templateId
	 * @param templateName
	 * @param relationTemplateId
	 * @param sortnum
	 * @return
	 */
	@Override
	public Integer addTemplateRelation(Long templateId, String templateName, String relationTemplateId,
			String sortnum) {
		
		return templateRelationDao.addTemplateRelation(templateId, templateName, Convert.toLong(relationTemplateId), sortnum);
	}


	/**
	 * 删除
	 * @param templateId
	 * @param relationTemplateId
	 * @return
	 */
	@Override
	public Integer removeTemplateRelation(Long templateId, Long relationTemplateId) {
		
		return templateRelationDao.removeTemplateRelation(templateId);
	}



	/**
	 * 查询
	 * @param templateName
	 * @return
	 */

	@Override
	public TemplateRelation queryTemplateRelation(String templateName) {
		
		return templateRelationDao.queryTemplateRelation(templateName);
	}

	/**
	 * 保存或更新模板关联关系
	 * @param staticStrategy
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor=Exception.class)
	@Override
	public void saveOrUpdateTemplateRelation(StaticStrategy staticStrategy) {

		List<String> fileNameList = staticStrategy.getFileName();

		if(ObjectUtil.isNull(staticStrategy.getTemplateId())){
			return;
		}

		if (CollectionUtil.isNotEmpty(fileNameList) && fileNameList.size() > 0){
			fileNameList.removeAll(Collections.singleton(null));
		}

		templateRelationDao.removeTemplateRelation(staticStrategy.getTemplateId());

		if (CollectionUtil.isEmpty(fileNameList)) {
			return;
		}

		fileNameList.forEach(item -> {
			TemplateManage templateManage = templateManageDao.querfyTemplateManage(null, item);
			if (templateManage == null) {
				return;
			}
			templateRelationDao.addTemplateRelation(staticStrategy.getTemplateId(), staticStrategy.getTemplateName(),
					templateManage.getTemplateId(), "1");

		});
	}



}
